import React, { useState, useEffect, useRef } from 'react'
import {
    Button,
    Modal,
    message,
    Tooltip,
    Space,
    Tag
} from 'antd'
import {
    DeleteOutlined,
    UnorderedListOutlined,
    RollbackOutlined,
    ExclamationCircleOutlined
} from '@ant-design/icons'
import { getAllBank, getAllCategoryServiceInformation, getEventInformation } from '../../../utils/request/get'
import { addBankRecord, addCategory, addCategoryService, addService } from '../../../utils/request/post'
import { updateCategoryService } from '../../../utils/request/put'
import { deleteServiceById } from '../../../utils/request/delete'
import MyTable from '../../../components/newsSandBox/MyTable'
import SearchItem from '../../../components/newsSandBox/SearchItem'
import { assignUndefinedValue, copy } from '../../../utils/common'
import CategoryServiceForm from '../../../components/serviceManage/CategoryServiceForm'
import { formatTimeLimit } from '../../../utils/time'
import { findIdByName } from '../../../utils/array'

const { confirm } = Modal

export default function Category_Service() {
    const [dataSource, setDataSource] = useState([])
    const [showData, setShowData] = useState([])
    const [categories, setCategories] = useState([])
    const [services, setServices] = useState([])
    const [header, setHeader] = useState([])
    const [circulations, setCirculations] = useState([])
    const [types, setTypes] = useState([])
    const [risks, setRisks] = useState([])
    const [currentId, setCurrentId] = useState(-1)
    const [total, setTotal] = useState(0)
    const [isModalVisible, setIsModalVisible] = useState(false)
    const [isAddVisible, setIsAddVisible] = useState(false)
    const [selectChanged, setSelectChanged] = useState(false)
    const addForm = useRef(null)
    const updateForm = useRef(null)

    useEffect(() => {
        async function fetchData() {
            const { list, categories, services, headers } = await getAllCategoryServiceInformation()
            const { circulations, types, risks } = await getEventInformation()
            setCategories(categories)
            setServices(services)
            setCirculations(circulations)
            setTypes(types)
            setRisks(risks)
            setHeader(headers[0])
            if (list) {
                setDataSource(list)
                setShowData(list)
            }
        }
        fetchData()
    }, [])

    const deleteData = (item) => {
        setShowData(showData.filter(data => data.id !== item.id));
        deleteServiceById(item.id)
    }

    const showConfirm = (type, item) => {
        let obj = {
            icon: <ExclamationCircleOutlined />,
        }
        switch (type) {
            case 'CANCEL':
                obj.title = '您确定要取消吗?'
                obj.onOk = function () { }
                obj.onCancel = function () { console.log('Cancel'); }
                break
            case 'DELETE':
                obj.title = '您确定要删除吗?'
                obj.cancelText = '取消'
                obj.okText = '确定'
                obj.onOk = function () { deleteData(item); }
                obj.onCancel = function () { console.log('Cancel'); }
                break
            default: break
        }
        confirm(obj)
    };

    const openModal = (item) => {
        // console.log(item);
        setIsModalVisible(true)
        setCurrentId(item.id)
        // 防止在modal组件加载之前就设置值
        setTimeout(() => {
            updateForm.current.setFieldsValue({ ...item })
        }, 0)
    }

    const columns = [
        {
            title: 'ID',
            dataIndex: 'id',
            width: 40,
            render: (id) => {
                return <b>{id}</b>
            }
        },
        {
            title: header['categoryName'],
            dataIndex: 'categoryName',
            width: 120,
            onCell: record => ({
                onClick: () => {
                    copy(record.Category.title)
                }
            }),
            sorter: (a, b) => {
                // 按 id 升序排列
                return a.Category.id - b.Category.id
            },
            filters: [...categories.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => {
                // value 是要筛选的内容 record 是所有内容
                // console.log(value, record);
                // console.log(record);
                // 只展示true的部分
                return record.Category.title.indexOf(value) === 0
            }
        },
        {
            title: header['serviceName'],
            dataIndex: 'serviceName',
            width: 110,
            onCell: record => ({
                onClick: () => {
                    copy(record.Service.title)
                }
            }),
            sorter: (a, b) => {
                // 按 id 升序排列
                return a.Service.id - b.Service.id
            },
            filters: [...services.map(item => ({
                text: item.title, value: item.title,
            }))],
            onFilter: (value, record) => record.Service.title.indexOf(value) === 0
        },
        {
            title: header['circulation'],
            dataIndex: 'circulation',
            width: 70
        },
        {
            title: header['type'],
            dataIndex: 'type',
            width: 70,
        },
        {
            title: header['risk'],
            dataIndex: 'risk',
            width: 70,
            render: (level) => {
                switch (level) {
                    case "暂无":
                        return <Tag color='green'>{level}</Tag>
                    case "低等":
                        return <Tag color='orange'>{level}</Tag>
                    case "中等":
                        return <Tag color='purple'>{level}</Tag>
                    case "高等":
                        return <Tag color='red'>{level}</Tag>
                    default:
                        return <Tag color='error'>{level}</Tag>
                }
            }
        },
        {
            title: header['timeLimit'],
            dataIndex: 'timeLimit',
            width: 100,
            sorter: (a, b) => {
                return a.timeLimit - b.timeLimit
            },
            render: (value) => {
                return formatTimeLimit(value)
            }
        },
        {
            title: header['bankName'],
            dataIndex: 'name',
            width: 100
        },
        {
            title: header['owner'],
            dataIndex: 'owner',
            width: 120
        },
        {
            title: header['number'],
            dataIndex: 'number',
            width: 110
        },
        {
            title: '操作',
            width: 100,
            render: (record) => {
                return (
                    <div>
                        <Button
                            danger onClick={() => showConfirm("DELETE", record)}
                            shape="circle" icon={<DeleteOutlined />}>
                        </Button>&nbsp;&nbsp;
                        <Button
                            shape="circle"
                            icon={<UnorderedListOutlined />}
                            type="primary"
                            onClick={() => { openModal(record) }}></Button>
                    </div>
                )
            },
        }
    ]

    const handleUpdateOk = async () => {
        updateForm.current.validateFields().then(value => {
            console.log(value);
            setIsModalVisible(false)
            updateForm.current.resetFields()
            value = {
                ...value,
                circulationId: findIdByName(circulations, value.circulation),
                typeId: findIdByName(types, value.type),
                riskId: findIdByName(risks, value.risk)
            }
            updateCategoryService(currentId, value).then(async res => {
                const data = res.data.category_service
                if (data) {
                    setShowData(showData.map(item => {
                        if (item.id === currentId) {
                            return { ...item, ...value }
                        }
                        return item
                    }))
                    message.success('修改成功')
                } else {
                    message.error('修改失败')
                }
            })
        })
    }

    const findBankId = (banks, string) => {
        if (banks.length === 0) return 0
        for (let i = 0; i < banks.length; i++) {
            const element = banks[i];
            if (element.name === string && element.owner === string && element.number === string) {
                return element.id
            }
        }
        return 0
    }

    const checkBank = async (value) => {
        const { number, owner, name } = value
        const bankRes = await getAllBank()
        const list = bankRes.data.banks
        console.log(value);
        // 如果任一有值
        if (number || owner || name) {
            if (number !== '不用录入') {
                const res = await addBankRecord({ number, owner, name })
                if (res) {
                    const { id } = res.data.bank
                    return {
                        ...value,
                        bankId: id
                    }
                }
            } else {
                return {
                    ...value, bankId: findBankId(list, "不用录入")
                }
            }
        }

        return {
            ...value, bankId: findBankId(list, "")
        }
    }

    const addFormMethod = () => {
        addForm.current.validateFields().then(async value => {
            setIsAddVisible(false)
            addForm.current.resetFields()

            // bank信息
            value = await checkBank(value)
            // console.log(value);
            const { categoryName, serviceName } = value
            const cateRes = await addCategory({ title: categoryName })
            const serviceRes = await addService({ title: serviceName })
            // 赋值
            const name = assignUndefinedValue(value.name)
            const number = assignUndefinedValue(value.number)
            const owner = assignUndefinedValue(value.owner)
            // 新增对象
            const obj = {
                ...value,
                circulationId: findIdByName(circulations, value.circulation),
                typeId: findIdByName(types, value.type),
                riskId: findIdByName(risks, value.risk),
                categoryId: cateRes.data.category.id,
                serviceId: serviceRes.data.service.id,
                name, owner, number
            }
            addCategoryService(obj).then(async res => {
                const data = res.data.category_service
                const { id } = data
                if (data) {
                    setShowData([...showData, { ...obj, id }])
                    message.success('添加成功')
                } else {
                    message.error('添加失败')
                }
            })

        }).catch(err => { showError(err) })
    }

    const showError = (err) => {
        const errors = err.errorFields
        if (errors.length > 0) {
            message.warning(errors[0].errors[0])
        }
    }

    const handleCancel = () => {
        setIsModalVisible(false)
    }

    const handleTableChange = (pagination, filters, sorter, extra) => {
        let showDatas = dataSource;

        // 遍历 filters 对象中的所有属性
        Object.keys(filters).forEach(filterKey => {
            const filterValues = filters[filterKey];

            if (filterValues && filterValues.length > 0) {
                showDatas = showDatas.filter(item => {
                    // 使用 indexOf 判断是否包含筛选条件
                    return filterValues.some(value => item[filterKey].indexOf(value) === 0);
                });
            }
        });

        // 更新显示数据和总数
        setShowData(showDatas);
        setTotal(showDatas.length);
    }

    /**
         * 
         * @param {搜索的类型} type 
         * @param {搜索的值} value 
         * @returns 同一类型下与搜索值相等的结果
         */
    const searchWithType = (type, value) => {
        setSelectChanged(true)
        // console.log(type);
        // console.log(value);
        const result = dataSource.filter(element => {
            const elementValue = element[type]
            if (typeof elementValue === 'number') {
                return element[type].toString().includes(value)
            }
            return elementValue.includes(value)
        });
        return result
    }

    const handleSearchFinish = (value, name) => {
        // console.log(name);
        const filteredData = searchWithType(name, value)
        setShowData(filteredData)
        setTotal(filteredData.length)
    }

    // 处理点击返回按钮的函数
    const handleReturnButtonClick = () => {
        // 恢复原始表格状态
        setShowData(dataSource);
        setTotal(dataSource.length);
        setSelectChanged(false); // 确保监测表格变化的状态正常
    };

    return (
        <>
            <Button
                type="primary"
                style={{ marginBottom: '5px' }} onClick={() => setIsAddVisible(true)}>添加办理项</Button>
            <div className='search-area' style={{ marginLeft: '10px' }}>
                <Space size='small'>
                    {/* 返回按钮 */}
                    <Tooltip placement="top" title={'点击清空'} >
                        <Button icon={<RollbackOutlined />} onClick={handleReturnButtonClick} />
                    </Tooltip>
                    <SearchItem title='主项名' name='categoryName' onFinish={handleSearchFinish} />
                    <SearchItem title='办理项名' name='serviceName' onFinish={handleSearchFinish} />
                </Space>
            </div>
            <MyTable
                total={total}
                pageSize={10}
                columns={columns}
                dataSource={showData}
                onChange={selectChanged ? null : handleTableChange}
                params={{
                    size: 'middle',
                    bordered: true,
                    rowClassName: { textAlign: 'center' },
                    scroll: {
                        x: 1000,
                        y: 420,
                    }
                }}
            />
            <Modal
                title="修改办理项"
                cancelText="取消"
                okText="确定"
                open={isModalVisible}
                onOk={handleUpdateOk}
                onCancel={handleCancel}>
                <CategoryServiceForm ref={updateForm} isUpdate={true} header={header}></CategoryServiceForm>
            </Modal>
            <Modal
                className='modal'
                open={isAddVisible}
                title="添加办理项"
                okText="完成"
                cancelText="取消"
                onCancel={() => setIsAddVisible(false)}
                onOk={() => addFormMethod()}
            >
                <CategoryServiceForm ref={addForm} header={header}></CategoryServiceForm>
            </Modal>
        </>
    )
}